package com.qf.kady.ssm.controller;

import com.qf.kady.ssm.entity.ResultVO;
import com.qf.kady.ssm.pojo.Reader;
import com.qf.kady.ssm.service.ReaderService;
import com.qf.kady.ssm.utils.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

/**
 * \* Created with IntelliJ IDEA.
 * \* User: kady
 * \* Date: 2021/4/22
 * \* Time: 13:50
 * \* 千峰JAVA2101班
 * \* Description: 书控制层
 * \
 */
@Controller
@RequestMapping("/admin")
public class ReaderController {

    @Autowired
    private ReaderService readerService;

    @RequestMapping("/allreaders.html")
    public ModelAndView showAdminReaders(String searchWord){
        List<Reader> resList = readerService.getReaderListByCondition(searchWord);
        ModelAndView mav = new ModelAndView();
        mav.addObject("readers",resList);
        mav.setViewName("admin/admin_readers");
        return mav;
    }

    @RequestMapping("/reader_add.html")
    public ModelAndView toAdminAddReader(Long readerId){
        ModelAndView mav = new ModelAndView();
        mav.setViewName("admin/admin_reader_add");
        return mav;
    }

    @RequestMapping("/reader_edit.html")
    public ModelAndView toAdminUpdateReade(Long readerId){
        Reader reader = readerService.getReaderDetailById(readerId);
        ModelAndView mav = new ModelAndView();
        mav.addObject("readerInfo",reader);
        mav.setViewName("admin/admin_reader_edit");
        return mav;
    }

    @RequestMapping("/reader_add_do.html")
    public ModelAndView addReade(Reader reader, Model model){
        reader.setPassword(MD5Util.md5(reader.getPassword()));
        boolean res = readerService.addReader(reader);
        if(res){
            model.addAttribute("succ","添加成功");
        }else{
            model.addAttribute("error","添加失败");
        }
        return showAdminReaders(null);
    }

    @RequestMapping("/reader_edit_do.html")
    public ModelAndView updateReade(Reader reader, Model model){
        boolean res = readerService.updateReader(reader);
        if(res){
            model.addAttribute("succ","更新成功");
        }else{
            model.addAttribute("error","更新失败");
        }
        return showAdminReaders(null);
    }

    @RequestMapping("/reader_delete.html")
    public ModelAndView deleteReade(Long readerId, Model model){
        ResultVO resultVO = readerService.deleteReader(readerId);
        if(resultVO.isSuccess()){
            model.addAttribute("succ",resultVO.getMessage());
        }else{
            model.addAttribute("error",resultVO.getMessage());
        }
        return showAdminReaders(null);
    }
}
